package com.etc.service.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.etc.dao.AlbumDao;
import com.etc.dao.MusiLyricDao;
import com.etc.dao.MusicDao;
import com.etc.dao.SinggerDao;
import com.etc.dao.impl.AlbumDaoImpl;
import com.etc.dao.impl.MusiLyricDaoImpl;
import com.etc.dao.impl.MusicDaoImpl;
import com.etc.dao.impl.SinggerDaoImpl;
import com.etc.entity.Album;
import com.etc.entity.Languages;
import com.etc.entity.Mood;
import com.etc.entity.MusicInfo;
import com.etc.entity.MusicLyric;
import com.etc.entity.MusicStyle;
import com.etc.entity.PageInfo;
import com.etc.entity.Region;
import com.etc.entity.Scene;
import com.etc.entity.Singger;
import com.etc.entity.Theme;
import com.etc.service.MusicService;
import com.etc.util.SimpleUtils;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

public class MusicServiceImpl implements MusicService{
	private MusicDao musicDao = new MusicDaoImpl();
	private MusiLyricDao musiLyricDao = new MusiLyricDaoImpl();
	private SinggerDao singgerDao = new SinggerDaoImpl();
	private AlbumDao albumDao = new AlbumDaoImpl();
	
	@Override
	public List<MusicInfo> findBysongSleetId(Integer broadcastingStationId) {
		// TODO Auto-generated method stub
		return musicDao.findBysongSleetId(broadcastingStationId);
	}
	
	@Override
	public MusicInfo findByid(Integer musicId) {
		return musicDao.findByid(musicId);
	}
	
	@Override
	public List<MusicInfo> findByUserId(Integer userId) {
		return musicDao.findByUesrId(userId);
	}
	
	// ============================================ admin 操作  Service ======================================
	

	@Override
	public boolean addSong(MusicInfo musicInfo) {
		// 创建一个新的歌曲对象
		MusicInfo mus = new MusicInfo();
		mus.setMusicId(musicInfo.getMusicId());
		mus.setMusicName(musicInfo.getMusicName());
		// 对歌曲信息进行判断
		// 1.对首字母的处理
		String musicName = musicInfo.getMusicName();
		SimpleUtils obj = new SimpleUtils();
		String initials = obj.String2Alpha(musicName.substring(0,1));
		mus.setInitials(initials);
		// 2.对歌手进行处理（调dao：通过歌手名查找歌手id）
		String singgerName =musicInfo.getSingger().getSinggerName();
		if (singgerName!=null) {
			// 如果存在则设置为数据库中的id，如果不存在则添加一个新的歌手
			Singger singger = singgerDao.finSinggerBySingerName(singgerName);
			if (singger != null) {
				Integer singgerId = singger.getSinggerId();
				singger.setSinggerId(singgerId);
				mus.setSingger(singger);
			}else {
				   singger = new Singger();
				   singger.setSinggerName(singgerName);
				   singger.setSinggerImgPath(null);
				   singger.setGender(null);
				   singger.setBirthday(null);
				   singger.setOccupation(null);
				   singger.setNationality(null);
				   singger.setBirthplace(null);
				   MusicStyle musicStyle = new MusicStyle();
				   musicStyle.setStyleName(null);
				   musicStyle.setStyleId(null);
				   singger.setMusicStyle(musicStyle );
				   Region region = new Region();
				   region.setRegionName(null);
				   region.setRegionId(null);
				   singger.setRegion(region);
				   singgerDao.addSinger(singger);
			}
		}else {
			Singger singger = new Singger();
			singger.setSinggerId(null);
			mus.setSingger(singger );
		}
		// 3.对专辑进行处理（调dao：通过专辑名查找专辑id）
		String albumName = musicInfo.getAlbum().getAlbumName();
		if (albumName!= null) {
			// 如果存在则设置为数据库中的id，如果不存在则添加一个新的专辑
			Album album = albumDao.findAlbumIdByName(albumName);
			if (album != null) {
				Integer albumId = album.getAlbumId();
				album.setAlbumId(albumId);
				mus.setAlbum(album);
			}else {
				// 创建一个新的专辑
				album = new Album();
				album.setAlbumName(albumName);
				album.setSinggerId(null);
				album.setAlbumImgPath(null);
				albumDao.addAlbum(album);
			}
		}else {
			Album album = new Album();
			album.setAlbumId(null);
			mus.setAlbum(album );
		}
		// 4.如果各选项
		if (musicInfo.getMusicStyle().getStyleId()!=0) {
			MusicStyle musicStyle = new MusicStyle();
			musicStyle.setStyleId(musicInfo.getMusicStyle().getStyleId());
			mus.setMusicStyle(musicStyle );
		}
		if (musicInfo.getTheme().getThemeId()!=0) {
			Theme theme = new Theme();
			theme.setThemeId(musicInfo.getTheme().getThemeId());
			mus.setTheme(theme);
		}
		if (musicInfo.getMood().getMoodId() != 0) {
			Mood mood = new Mood();
			mood.setMoodId(musicInfo.getMood().getMoodId());
			mus.setMood(mood);
		}
		if (musicInfo.getScene().getSceneId() != 0) {
			Scene scene = new Scene();
			scene.setSceneId(musicInfo.getScene().getSceneId());
			mus.setScene(scene);
		}
		if (musicInfo.getLanguages().getLanguagesId() != 0) {
			Languages languages = new Languages();
			languages.setLanguagesId(musicInfo.getLanguages().getLanguagesId());
			mus.setLanguages(languages);
		}
		if (musicInfo.getReleaseTime() != null && !"".equals(musicInfo.getReleaseTime())) {
			mus.setReleaseTime(musicInfo.getReleaseTime());
		}
		// 对歌词进行判断
		if (musicInfo.getMusicLyric().getMusicLyrName() != null) {
			// 4位随机数
			int random = (int) ((Math.random() * 9 + 1) * 1000);
			MusicLyric musicLyric = new MusicLyric();
			musicLyric.setMusicLyrId(random);
			// 设置歌词名为歌曲名
			musicLyric.setMusicLyrName(musicInfo.getMusicLyric().getMusicLyrName());
			mus.setMusicLyric(musicLyric);
			// 对歌词表进行添加数据（调dao：添加歌词数据）  -> 此处的歌词id 设置为歌曲id
			musiLyricDao.addMusiLyric(musicLyric);
		}
		if (musicInfo.getMusicImgPath() != null) {
			mus.setMusicImgPath(musicInfo.getMusicImgPath());
		}
		if (musicInfo.getMusicMp3Path() != null) {
			mus.setMusicMp3Path(musicInfo.getMusicMp3Path());
			// 对音频文件的时长做处理
			File source = new File("D:\\file\\MP3\\"+musicInfo.getMusicMp3Path());
	        Encoder encoder = new Encoder();
	        try {
	            MultimediaInfo m = encoder.getInfo(source);
	            long ls = m.getDuration();
	            int min = (int) (ls/60000) ;
	            String minute= String.format("%02d", min);
	            StringBuilder sb = new StringBuilder();
	            sb.append(minute).append(":").append((ls/1000-ls/60000*60));
	            // 设置上传音频的时长
	            mus.setDuration(sb.toString());
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		int n = musicDao.addSong(mus);
		return n > 0 ? true : false;
	}
	@Override
	public boolean modifySongInfo(MusicInfo musicInfo) {
		int n = musicDao.modifySingerInfo(musicInfo);
		return n > 0 ? true : false;
	}
	@Override
	public boolean deleteSongById(Integer musicId) {
		int n = musicDao.deleteSongById(musicId);
		return  n > 0 ? true : false;
	}

	@Override
	public MusicInfo getMusicInfoById(Integer musicId) {
		return musicDao.findSongInfoById(musicId);
	}

	@Override
	public PageInfo<MusicInfo> getSongInfoBySongName(String musicName, int pageNum, int pageSize) {
		List<MusicInfo> data = musicDao.findSongInfoInfoBySongName(musicName, pageNum, pageSize);
		Integer total = musicDao.countBySongName(musicName);
		PageInfo<MusicInfo> pageInfo = new PageInfo<MusicInfo>(data, pageNum, pageSize, total);
		return pageInfo;
	}

	@Override
	public List<Map<String, Object>> getLikeCountGrounpByStyle() {
		return musicDao.findLikeCountGrounpByStyle();
	}

	/**
	 * 根据歌手ID查询music
	 */
	@Override
	public PageInfo<MusicInfo> getsongListBySingerId(Integer singgerId, int pageNum, int pageSize) {
		
		List<MusicInfo> data = musicDao.findMusicBySinggerId(singgerId, pageNum, pageSize);
		
		Integer total = musicDao.countMusicBySinggerId(singgerId);
		PageInfo<MusicInfo> pageInfo = new PageInfo<MusicInfo>(data, pageNum, pageSize, total);
		return pageInfo;
	}
	@Override
	public List<MusicInfo> exportMusicInfos() {
		return musicDao.findAll();
	}

	@Override

	public PageInfo<MusicInfo> getSongListByKeyWord(String keyWord, int pageNum, int pageSize) {
List<MusicInfo> data = musicDao.findByKeyWord(keyWord, pageNum, pageSize);
		
		Integer total = musicDao.countMusicByKeyWord(keyWord);
		PageInfo<MusicInfo> pageInfo = new PageInfo<MusicInfo>(data, pageNum, pageSize, total);
		return pageInfo;
	}

	

	public List<MusicInfo> getHalfYearMusic(String languagesName) {
		return musicDao.findHalfYearMusic(languagesName);
	}

	@Override
	public List<MusicInfo> getListByCondition(Integer condition) {
		return musicDao.findListByCondition(condition);
	}

	@Override
	public List<Map<String, Object>> getStyleCount() {
		return musicDao.findStyleCount();
	}


	
}
